﻿using System;
using System.Collections.Generic;
using System.IO;

public class Library {
	// === Public =====================================================================================================
	public static Library Instance { get; private set; }
	public LibraryBase Work { get; private set; }

	public void SetWorkLibrary(LibraryBase library) {
		if(library == null) {
			throw new Exception("library is null");
		}
		if(Work != null) {
			Work.SaveToDiskAsXml();
		}
		Work = library;
		SendChangeEvent();
	}
	public void Save() {
		if(Work != null) {
			Work.SaveToDiskAsXml();
		}
	}
	public void SaveAndCloseLibrary() {
		if(Work != null) {
			Work.SaveToDiskAsXml();
			Work = null;
			SendChangeEvent();
		}
	}

	public void AddListener(MyEvent callback) {
		if(callback == null) {
			throw new Exception("callback is null");
		}
		_listeners += callback;
	}

	public void RemoveListener(MyEvent callback) {
		if(callback == null) {
			throw new Exception("callback is null");
		}
		_listeners -= callback;
	}

	public List<string> GetLibNames() {
		var result = new List<string>();
		foreach(var fi in new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles("*.xml")) {
			if(Directory.Exists(fi.FullName.Remove(fi.FullName.Length - fi.Extension.Length))) {
				result.Add(fi.Name.Remove(fi.Name.Length - fi.Extension.Length));
			}
		}
		return result;
	}

	// === Private ====================================================================================================
	private MyEvent _listeners;

	static Library() {
		Instance = new Library();
	}

	private Library() { }

	private void SendChangeEvent() {
		if(_listeners != null) {
			_listeners();
		}
	}
}
